// pages/chat/chat.js
import { formatTime } from "../../utils/util.js";
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chat_users: [],
    user_id: 0,
    isScroll: true,
    chat_list: [],
    chat_length: 0,
    touchStartPageX: 0,
    scrollLeft: [],
    numbers: [],
    label_time: [],
    temp: 0,
    isloadList: true,
    show: [],
    isShow: true,
    /*tabbar: {}*/
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    qq.showShareMenu({
      showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
    });
    /*wx.hideTabBar();
    app.editTabBar();*/
    if(app.globalData.nowColor == "#0086ff"){
      var nowColor="#1aad19";
      that.setData({
        nowColor:nowColor
      })
    }else{
      that.setData({
      nowColor:app.globalData.nowColor
    })
    }
    wx.getSystemInfo({
      success: function (res) {
        //rpx
        that.setData({
          heightScreen: res.windowHeight * (750 / res.windowWidth),

        });
        console.log(that.data.heightScreen);
      }
    });
    var user_id = wx.getStorageSync("user_id"); /*wx.getStorageSync("user_id");*/
    that.setData({
      user_id: user_id,
      nowSkinUrl: app.globalData.nowSkinUrl
    });
    that.loadChatList();


  },

  //一个小算法:时间变数字方法,为了与当前时间比较
  time_num: function (time) {
    var that = this;
    var year_and_month = [];
    for (var i = 0; i < 10; i++) {
      year_and_month[i] = time[i];
    }
    var temp = year_and_month[5] * 1000 + year_and_month[6] * 100 + year_and_month[8] * 10 + year_and_month[9] * 1;
    that.setData({
      temp: temp
    });
  },

  //更新最后聊天时间，将时间显示在列表栏右上角
  loadChatList_time: function (chat_list) {
    var that = this;
    var time = formatTime(new Date());
    that.time_num(time);
    var present_time = that.data.temp;
    var chat_last_time = 0;
    var label_time = [];
    for (var i = 0; i < chat_list.length; i++) {
      var created_time = chat_list[i].created_time;
      that.time_num(created_time);
      chat_last_time = that.data.temp;
      //console.log(chat_last_time);
      if (present_time == chat_last_time) {
        var minute_and_second = "";
        for (var index = 11; index < 16; index++) {
          minute_and_second = minute_and_second + created_time[index];
        }
        label_time[i] = minute_and_second;
      } else if (present_time - 1 == chat_last_time) {
        label_time[i] = "昨天";
      } else {
        var month_and_day = "";
        for (var index = 5; index < 10; index++) {
          month_and_day = month_and_day + created_time[index];
        }
        label_time[i] = month_and_day;
      }
    }
    that.setData({
      label_time: label_time
    });
  },


  //将编码后的八进制的emoji表情重新解码成十六进制的表情字符

  entitiesToUtf16: function (str) {

    return str.replace(/&#(\d+);/g, function (match, dec) {

      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;

      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;

      return String.fromCharCode(H, L);

    });

  },

  // 从服务器实时刷新聊天列表
  loadChatList: function () {
    var that = this;
    var id_list = [];
    var chat_list = [];
    var show = [];
    var flag = 0;
    wx.request({
      url: app.globalData.targetUrl + 'wx/chat_list',
      method: 'get',
      header: {
        'content-type': 'application/json'
      },
      data: {
        'user_id': that.data.user_id
      },
      success: res => {
        console.log("res.data.data");
        console.log(res.data.data);
        chat_list = res.data.data;
        for (var i = 0; i < chat_list.length; i++) {

          chat_list[i].last_chat = that.entitiesToUtf16(chat_list[i].last_chat);
        }
        that.loadChatList_time(chat_list);
        /*if(that.data.label){
          for(var i = 0; i < chat_list.length; i++){
            show[i] = false;
          }
          that.setData({
            label:false
          })
        }else{

        }*/
        for (var i = 0; i < chat_list.length; i++) {
          show[i] = false;
        }
        var raw_chat_list = that.data.chat_list;
        var raw_show = that.data.show;
        console.log("raw_show");
        console.log(raw_show);
        console.log("raw_chat_list");
        console.log(raw_chat_list);
        // 如果是一样的长度
        if (raw_chat_list.length == chat_list.length) {
          for (var i = 0; i < raw_chat_list.length; i++) {
            // 解决顺序变动的问题
            for (var j = 0; j < chat_list.length; j++) {
              // 进行定位
              if (raw_chat_list[i].with_id == chat_list[j].with_id) {
                // 原先的保留
                if (raw_show[i]) {
                  show[j] = true;
                }
                // 如果消息不一致, 且不是自己发的, 判定为新消息, 并更改排序
                if (raw_chat_list[i].created_time !== chat_list[j].created_time) {
                  that.setData({
                    isloadList: true
                  });
                  if (chat_list[j].is_mine == 0) {
                    flag = 1;
                    var label = wx.getStorageSync('label');
                    if (label == 0) {    //设置在index.js
                      show[j] = true;
                    } else {
                      show[j] = false;
                      label = 0;
                      wx.setStorageSync('label', label);
                    }
                  }
                  wx.request({
                    url: app.globalData.targetUrl + 'wx/chat_list/',
                    method: 'post',
                    header: {
                      'Content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                      'user_id': that.data.user_id,
                      'with_user_id': chat_list[j].with_id
                    },
                    success: res => {
                      console.log("change");
                      // 更改排序成功
                      wx.request({
                        url: app.globalData.targetUrl + 'wx/chat_list',
                        method: 'get',
                        header: {
                          'content-type': 'application/json'
                        },
                        data: {
                          'user_id': that.data.user_id
                        },
                        success: function (res) {
                          console.log(res);
                          chat_list = res.data.data;
                          for (var i = 0; i < chat_list.length; i++) {
                            chat_list[i].last_chat = that.entitiesToUtf16(chat_list[i].last_chat);
                          }
                          var id = []
                          that.setData({
                            chat_list: chat_list,

                          });
                          for (var i = 0; i < chat_list.length; i++) {
                            var numberk = "numbers[" + i + "]";
                            id[i] = chat_list[i].with_id;
                            id_list.push(chat_list[i].with_id);
                            that.setData({
                              [numberk]: i
                            })
                          }
                          console.log(id);
                          wx.request({
                            url: app.globalData.targetUrl + 'users/',
                            method: "get",
                            data: {
                              'user_list': id                  /////
                            },
                            success: function (res) {
                              console.log("this is");
                              console.log(res.data);
                              that.setData({
                                chat_users: res.data.data
                              });
                            }
                          });
                        }
                      })
                    }
                  });
                } else {
                  that.setData({
                    isloadList: false
                  })
                }
              }
            }
          }
        }
        if (that.data.isloadList || flag == 1) {
          that.setData({
            show: show,
            chat_list: chat_list,

            numbers: []  //置空防止多渲染了
          });
          for (var i = 0; i < chat_list.length; i++) {
            var numberk = "numbers[" + i + "]";
            id_list[i] = chat_list[i].with_id;
            that.setData({
              [numberk]: i
            })
          }
          //wx.setStorageSync('show', show);
          console.log(id_list)
          wx.request({
            url: app.globalData.targetUrl + 'users/',
            method: "get",
            data: {
              'user_list': id_list
            },
            success: function (res) {
              console.log("---" + res.data);
              that.setData({
                chat_users: res.data.data
              });
            }
          });
        }
        /* console.log(show.length);
         for(var  i = 0 ; i < show.length; i++){
           if(show[i]){
             wx.showTabBarRedDot({
               index: 3,//index是让tabbar的第几个图标闪起来(从0开始的)，我现在是让第二个图片的红点闪
             })
             break;
           }
         }*/
      }
    })
  },

  // 进入聊天, 删除标记
  toChat: function (e) {
    var that = this;
    var from_user_id = that.data.user_id;
    var to_user_id = e.currentTarget.dataset.to_user_id;
    var idx = e.currentTarget.dataset.index;
    var chat_list = that.data.chat_list;
    var show = that.data.show;
    console.log(e)
    if (show[idx]) {
      show[idx] = false;
      chat_list[idx].is_mine = 0;   //同时防止下次刷新重新刷到
    }
    that.setData({
      show: show,
      chat_list: chat_list
    })
    wx.navigateTo({
      url: '/pages/chatPage/chatPage?from_user_id=' + from_user_id + '&to_user_id=' + to_user_id,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    that.setData({
      nowSkinUrl: app.globalData.nowSkinUrl,
    })
    if(app.globalData.nowColor == "#0086ff"){
      var nowColor="#1aad19";
      that.setData({
        nowColor:nowColor
      })
    }else{
      that.setData({
      nowColor:app.globalData.nowColor
    })
    }
    var is_Register = wx.getStorageSync('is_Register');
    if (!is_Register) {
      wx.showModal({
        title: '提示',
        content: '请先注册',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: "/pages/my/my"
            });
          }
        }
      })
    }
    /*var is_Register = wx.getStorageSync('is_Register');
    if (!is_Register) {
      wx.showModal({
        title: '提示',
        content: '请先注册',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: "/pages/my/my"
            });
          }
        }
      })
    }
    that.setData({
      isloadList: true,
      isShow: true
    })*/
    that.loadChatList();
    var len = 0;
    if (that.data.inverval != 0) {
      var times = 0
      var id = setInterval(function () {
        that.setData({
          interval: id,
          scrollLeft: []
        });
        if (that.data.isShow) {
          that.loadChatList();
        }
      }, 3000);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var isShow = false;
    var that = this;
    that.setData({
      isShow: isShow
    })
    console.log("chatlist停止刷新--onHide")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var isShow = false;
    var that = this;
    that.setData({
      isShow: isShow
    })
    console.log("chatlist停止刷新--onUnload")
  },

  /*左右滑动*/

  touchStart: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log(index);
    this.setData({
      touchStartPageX: e.changedTouches[0].pageX,
    })
  },

  touchEnd: function (e) {
    var index = e.currentTarget.dataset.index;
    let touchEndPageX = e.changedTouches[0].pageX;
    var left = "scrollLeft[" + index + "]";
    var offSetStartToEnd = touchEndPageX - this.data.touchStartPageX;
    if (offSetStartToEnd < 10 & offSetStartToEnd > -10) {
      return;
    };
    if (offSetStartToEnd > 10) {
      if (this.data.scrollLeft === 0) return;
      this.setData({
        [left]: 0
      });
    };
    if (offSetStartToEnd < -50) {
      this.setData({
        [left]: 60,
        isOnload: false
      })
    }
  },
  deleteTouchEnd: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var with_user_id = that.data.chat_list[index].with_id;
    console.log(index);
    console.log(with_user_id);
    wx.request({
      url: app.globalData.targetUrl + 'wx/chat_list/',
      method: 'post',
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'user_id': that.data.user_id,
        'with_user_id': with_user_id,
        'delete': '1'
      },
      success: function () {
        console.log("删除成功");
        var left = "scrollLeft[" + index + "]";
        that.setData({
          numbers: [],
          [left]: 0,
          isOnload: true,
          isloadList: true
        });
        that.loadChatList();
      }
    })
  }
})